package edu.nwmissouri.galaxygames;

import java.util.ArrayList;

import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;

public class SnapAfterFling implements OnScrollListener
{
    int currentFirstVisibleItem;
    int currentVisibleItemCount;
    int currentScrollState;
    int lvCenter;

    public SnapAfterFling(int lvHeight)
    {
	this.lvCenter = lvHeight/2;
    }
    
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
	    this.currentFirstVisibleItem = firstVisibleItem;
	    this.currentVisibleItemCount = visibleItemCount;
	}

	public void onScrollStateChanged(AbsListView view, int scrollState) {
	    this.currentScrollState = scrollState;
	    this.isScrollCompleted(view);
	 }

	private void isScrollCompleted(AbsListView lv) {
	    if (this.currentVisibleItemCount > 0 && this.currentScrollState == SCROLL_STATE_IDLE)
	    {
		    ArrayList<Integer> views = new ArrayList<Integer>();
		    int firstchillun = this.currentFirstVisibleItem;
		    int lastchillun = firstchillun+this.currentVisibleItemCount - 1;
		    for (int i = firstchillun; i <= lastchillun; i++)
		    {
			String s = (String) lv.getItemAtPosition(i);
			if (s != null)
			{
			    views.add(Integer.valueOf(s));
			}
		    }
		    if (views.size()/2 != 0)
		    {
			//Just pick the one in the middle.
			((LifeListView) lv).setSelectionFromTop(Integer.valueOf(views.get(views.size()/2)), LifeCounterFragment.selectionCenter);
		    }
		    else
		    {
			//Unsure which one is in middle, so let's figure it out.
			
			//Initialize variables, get numbers for calculations.
			int itemToCenter = 10;
			View v = lv.getChildAt(0);
			int itemHeight = v.getHeight();
			float[] centers = new float[this.currentVisibleItemCount];
			centers[0] = v.getY() + (itemHeight/2);
			
			//Get the center of each item.
			for (int i = 1; i < centers.length; i++)
			{
			    centers[i-1] = centers[i] + itemHeight;
			}
			
			
			
			//See how far they are from the center of the list view.
			for (int i = 0; i < centers.length; i++)
			{
			    centers[i] = lvCenter - centers[i];
			}
			
			//If negative invert.
			for (int i = 0; i < centers.length; i++)
			{
			    if (centers[i] < 0)
			    {
				centers[i] *= -1;
			    }
			}
			
			//See who's closest to the center.
			for (int i = 0; i < centers.length; i++)
			{
			    if (centers[i] < itemToCenter)
			    {
				itemToCenter = (int) centers[i];
			    }
			}
			
			//Center the view closer to the center.
			((LifeListView) lv).setSelectionFromTop(itemToCenter, LifeCounterFragment.selectionCenter);
		    }
	    }
	}

}
